/**
 * 用户管理：用户列表
 */

const express = require('express')
// 引入数据库连接池
const pool = require('../../db/db')
// 引入封装后的响应结果
const Response = require('../../utils/ResponseData')
// 引入表单验证模块joi
const Joi = require('joi')
const { required } = require('joi')

// 创建理由管理器
const router = express.Router()

/**
 * 用户查询查询接口
 * 请求url：http://localhost:3000/userList/get
 * 请求方式： GET
 */
router.get('/userList/get', async (req,res)=> {
    console.log(req.query)
    // 表单校验
    // 配置校验规则
    let schema = Joi.object({
        keywords: Joi.string(),
        page: Joi.number().required(),
        pageSize: Joi.number().integer().max(10).required()
    })
    let {error} = req.body

    if(error) {
        res.send(Response.error(error))
        return
    }
    // 校验通过
    try {
        let {page,pageSize,keywords} = req.query
        // 每页开始的位置
        let startIndex = (page - 1) * pageSize
        // 初始化page、pageSize、keywords
        pageSize = pageSize ? parseInt(pageSize) : 5
        page = page ? parseInt(page) : 1
        keywords = keywords ? keywords : ''

        // 编写sql，查询每页显示的数据
        const sql = `select * from (select * from user where u_name like ?)b1 limit ?, ?`
        const result = await pool.querySync(sql,[`%${keywords}%`,startIndex,pageSize])
        // 编写sql：查询总条数
        const sql2 = `select count(u_id) as count from (select * from user where u_name like ?)b1`
        const result2 = await pool.querySync(sql2,[`%${keywords}%`])
        console.log(result2)
        const total = result2[0].count
        // 将数据返回给前端
        res.send(Response.success({
            page: page,
            pageSize: pageSize,
            total,
            result
        }))
    } catch (e) {
        res.send(Response.error(e))
    }

})

/**
 * 删除用户接口
 * url: http://localhost:3000/user/delete
 * 
 */
router.get('/user/delete',(req,res) => {
    let {u_id} = req.query

    let schema = Joi.object({
        u_id: Joi.number().required()
    })
    let {error} = schema.validate(req.query)
    if(error) {
        res.send(Response.error(error))
        return
    }
    const sql = `delete from user where u_id=?`
    pool.query(sql,[u_id],(err,result) => {
        if (result && result.affectedRows > 0) {
            res.send(Response.success(null, '日志信息删除成功'))
        } else {
            res.send(Response.error('日志信息删除失败！'))
        }
    })
})


module.exports = router